<template>
  <el-card style="margin-bottom:140px">
    <!-- 头部 -->
    <div slot="header" class="clearfix">
      <b>{{cate===1?'新增试卷':'修改试卷'}}</b>
      <el-button
        style="float: right;"
        size="small"
        type="primary"
        plain
        @click="$emit('backPaper')"
      >返回列表</el-button>
    </div>
    <el-form label-width="130px" :model="formData" :rules="formRules" ref="form">
      <!-- 一 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="试卷名称" prop="paper_name">
            <el-input placeholder="请输入试卷名称" v-model="formData.paper_name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="试卷包含类型">
            <el-checkbox-group v-model="formData.quest_type">
              <el-checkbox
                label="1"
                class="qsType"
                @change="checked=>saveTempBeassessed(checked, 1)"
              >单选题</el-checkbox>
              <el-checkbox
                label="2"
                class="qsType"
                @change="checked=>saveTempBeassessed(checked, 2)"
              >多选题</el-checkbox>
              <el-checkbox
                label="3"
                class="qsType"
                @change="checked=>saveTempBeassessed(checked, 3)"
              >判断题</el-checkbox>
              <el-checkbox
                label="4"
                class="qsType"
                @change="checked=>saveTempBeassessed(checked, 4)"
              >简答题</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 二 -->
      <el-row>
        <el-col :span="6">
          <el-form-item label="归属学科">
            <el-select
              @change="changeHandler"
              v-model="formData.subject_id"
              placeholder="请选择学科"
              clearable
            >
              <el-option
                v-for="item in treeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="归属目录" prop="directory_id">
            <el-select v-model="formData.directory_id" placeholder="请选择目录" clearable>
              <el-option
                v-for="item in directoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="试卷状态" prop="show_state">
            <el-radio-group v-model="formData.show_state">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="试卷类型" prop="paper_type">
            <el-radio-group v-model="formData.paper_type">
              <el-radio :label="1">模拟卷</el-radio>
              <el-radio :label="2">考试卷</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 三 -->
      <el-row>
        <el-col :span="6">
          <el-form-item label="试卷总分">
            <el-input placeholder="请输入内容" v-model="formData.total_score">
              <template slot="append">分</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="及格分数">
            <el-input placeholder="请输入内容" v-model="formData.pass_score">
              <template slot="append">分</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="试卷难度">
            <el-select v-model="formData.difficulty" placeholder="请选择难度" clearable>
              <el-option label="简单" :value="1"></el-option>
              <el-option label="中等" :value="2"></el-option>
              <el-option label="较难" :value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 四 -->
      <el-row>
        <el-form-item label="选题信息">
          <el-table border :data="formData.check_question_list" empty-text="请勾选试卷包含题型，从而生成选题模板">
            <el-table-column label="题型" width="180px" prop="name"></el-table-column>
            <el-table-column label="选题信息">
              <template slot-scope="{row}">
                共
                <el-input
                  size="small"
                  style="width:60px"
                  autocomplete="off"
                  value="0"
                  v-model="row.num"
                  @input="changNum(row)"
                />题，每题
                <el-input
                  size="small"
                  style="width:60px"
                  autocomplete="off"
                  value="0"
                  v-model="row.score"
                />分,已选题数：
                <el-link type="primary">{{countList[row.type-1].length}}</el-link>题
                <el-button size="small" type="success" @click="lookQsFn(row.type)">看题</el-button>
                <el-button size="small" type="primary" @click="chooseFn(row.type)">选题</el-button>
                <span style="color:red" v-if="tipShow">选题数量和试题数量不一致</span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-row>
    </el-form>
    <el-row type="flex" justify="center">
      <el-button type="primary" @click="createFn">立即创建</el-button>
      <el-button>取消</el-button>
    </el-row>
    <ChooseQustion ref="ChooseQustion" :type="type" @getQsList="getQsList" @getLength="getLength" />
    <!-- 查阅试题弹窗 -->
    <el-dialog title="查阅试题" :visible.sync="showDialog" width="75%" v-if="showDialog">
      <el-table border :data="chayueList">
        <el-table-column label="试题内容">
          <template slot-scope="{row}">
            <el-row type="flex" align="middle">
              <el-col :span="2">
                <span class="tag2">ID：{{row.id}}</span>
              </el-col>
              <el-col :span="22">
                <span class="tag2">题干信息：</span>
                <el-link
                  :underline="false"
                  type="primary"
                  v-html="row.question"
                  @click="qsPreviewFn(row.id)"
                ></el-link>
              </el-col>
            </el-row>
            <el-row type="flex" align="middle">
              <el-col :span="4">
                <span class="tag2">归属学科：</span>
                {{row.subject_name}}
              </el-col>
              <el-col :span="4">
                <span class="tag2">归属目录：</span>
                {{row.directory_name}}
              </el-col>
              <el-col :span="7">
                <span class="tag2">标签信息：</span>
                {{row.tag_info[0]}}
              </el-col>
              <el-col :span="4">
                <span class="tag2">发布状态：</span>
                <el-tag type="success" size="small">上架</el-tag>
              </el-col>
              <el-col :span="4">
                <span class="tag2">发布时间：</span>
                {{row.check_time | formatDate}}
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <el-button circle icon="el-icon-delete" type="danger"></el-button>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 试题预览弹窗 -->
    <el-dialog
      title="试题预览"
      :visible.sync="previewShow"
      width="68%"
      v-if="previewShow"
      @close="preClose"
    >
      <el-divider content-position="center">基本信息</el-divider>
      <el-row type="flex" align="middle" style="line-height:30px">
        <el-col :span="10">
          <span class="tag2">试题编号：</span>
          {{previewQuestion.quest_num}}
        </el-col>
        <el-col :span="4">
          <span class="tag2">试题类型：</span>
          {{previewQuestion.quest_type===1?'选择题':previewQuestion.quest_type===2?"多选题":previewQuestion.quest_type===3?'判断题':'简答题'}}
        </el-col>
        <el-col :span="5">
          <span class="tag2">归属学科：</span>
          {{previewQuestion.subject_name}}
        </el-col>
        <el-col :span="5">
          <span class="tag2">归属目录：</span>
          {{previewQuestion.directory_name}}
        </el-col>
      </el-row>
      <el-row type="flex" align="middle" style="line-height:30px">
        <el-col :span="10">
          <span class="tag2">标题信息：</span>
          {{previewQuestion.tag_info[0]}}
          <!-- {{info}} -->
        </el-col>
        <el-col :span="4">
          <span class="tag2">发布状态：</span>

          <el-tag type="success" size="small">上架</el-tag>
        </el-col>
        <el-col :span="5">
          <span class="tag2">审核人：</span>
          {{previewQuestion.check_username}}
        </el-col>
        <el-col :span="5">
          <span class="tag2">审核状态：</span>
          <el-tag type="success" size="small">通过</el-tag>
        </el-col>
      </el-row>
      <el-row type="flex" align="middle" style="line-height:30px">
        <el-col :span="10">
          <span class="tag2">审核意见：</span>
          {{previewQuestion.check_remarks}}
        </el-col>
        <el-col :span="4">
          <span class="tag2">创建人：</span>
          {{previewQuestion.create_name}}
        </el-col>
        <el-col :span="5">
          <span class="tag2">难度系数：</span>
          {{previewQuestion.difficulty===1?'简单':previewQuestion.difficulty===2?"中等":"困难"}}
        </el-col>
        <el-col :span="5">
          <span class="tag2">发布时间：</span>
          {{previewQuestion.created_at | formatDate}}
        </el-col>
      </el-row>
      <!-- ---------------------------试题信息------------------------------------ -->
      <el-divider content-position="center">试题信息</el-divider>
      <el-row>
        <el-col :span="24">
          <span class="tag2">题干信息：</span>
          <el-link :underline="false" type="primary" v-html="previewQuestion.question"></el-link>
        </el-col>
        <el-col :span="24" style="margin-top:10px">
          <el-row type="flex" align="middle">
            <span class="tag2">选项信息：</span>
            <!-- 选择题 -->
            <span v-if="previewQuestion.quest_type===2">
              <el-checkbox
                v-for="item in options"
                :key="item.code"
                checked
              >{{item.code}}&nbsp;{{ item.content}}</el-checkbox>
            </span>
            <!-- 判断题 -->
            <span v-if="previewQuestion.quest_type===3">
              <el-checkbox :checked="previewQuestion.is_true_question===1">正确</el-checkbox>
              <el-checkbox :checked="previewQuestion.is_true_question===2">错误</el-checkbox>
            </span>
            <span v-if="previewQuestion.quest_type===4">简答题、无选项</span>
          </el-row>
        </el-col>
      </el-row>
      <!-- ---------------------------试题信息-------------------------------------->
      <!-- ---------------------------答案信息-------------------------------------->
      <el-divider content-position="center">答案信息</el-divider>
      <el-row type="flex">
        <span class="tag2">正确答案：</span>
        <el-link
          v-if="previewQuestion.quest_type===4"
          type="primary"
          :underline="false"
          v-html="previewQuestion.quest_answer"
        ></el-link>
        <span v-else>
          <el-link type="primary" :underline="false" v-html="previewQuestion.quest_answer"></el-link>
        </span>
      </el-row>
      <el-row type="flex" align="middle" style="margin-top:10px">
        <span class="tag2">答案解析：</span>
        <span v-if="previewQuestion.quest_type===4">暂无解析</span>
        <span v-html="previewQuestion.quest_remark"></span>
      </el-row>
      <!-- ---------------------------答案信息-------------------------------------->
    </el-dialog>
  </el-card>
</template>

<script>
import { getSubjectListApi, addPaperApi, editPaperApi } from '@/api/paper'
// 引入选择试题组件
import ChooseQustion from './ChooseQuestion.vue'

export default {
  name: 'AddPaper',
  props: {
    cate: {
      default: 1,
    },
  },
  components: {
    ChooseQustion,
  },
  created() {},
  computed: {
    qsNum() {
      return
    },
  },
  data() {
    return {
      previewQuestion: '', //试题预览的题目

      chayueList: [],
      showDialog: false, //查阅试题
      previewShow: false, //试题预览
      directoryList: [], //归属目录列表
      formData: {
        paper_name: '', //试卷名
        quest_type: [], //题目类型数组
        subject_id: '', //归属学科
        directory_id: '', //归属目录
        show_state: 1, //试卷状态
        paper_type: 1, //试卷类型
        total_score: 100, //试卷总分,
        pass_score: 60, //及格分数
        difficulty: '', //试卷难度、
        question_list: [], //选中的题目的id数组
        check_question_list: [], //选题信息
        question_data: [], //题目集合
      },
      formRules: {},
      //   归属学科
      treeList: [],
      //   题目类型的代号与名称对象
      typeList: [
        { type: 1, name: '单选题' },
        { type: 2, name: '多选题' },
        { type: 3, name: '判断题' },
        { type: 4, name: '简答题' },
      ],
      index: '',
      falseCheckList: {
        num: 0,
        score: 0,
      },
      type: 0, //传递给选题界面的题目类型
      countList: [
        { type: 1, length: 0 },
        { type: 2, length: 0 },
        { type: 3, length: 0 },
        { type: 4, length: 0 },
      ],
      tipShow: false, //选题数量不对
    }
  },

  created() {
    this.initData()
  },

  methods: {
    async initData() {
      this.treeList = await getSubjectListApi()
      // 调整题目数量
      if (this.cate === 2) {
        // 修改进来的
        this.formData.question_data.forEach((item) => {
          let idx = this.countList.findIndex(
            (it) => it.type === item.quest_type
          )
          this.countList[idx].length++
        })
        this.formData.directory_id = ''
      }
    },
    // 多选框事件
    saveTempBeassessed(checked, val) {
      if (checked) {
        console.log(this.typeList[val - 1].name)
        this.formData.check_question_list.push({
          type: val,
          name: this.typeList[val - 1].name,
          num: 0,
          score: 0,
          check_list: [],
        })
        // 排序
        this.formData.check_question_list.sort((a, b) => {
          return a.type - b.type
        })
      } else {
        let index = this.formData.check_question_list.findIndex((item) => {
          return item.type === val
        })
        this.formData.check_question_list.splice(index, 1)
      }
    },
    // 选题
    chooseFn(type) {
      let arr = this.formData.question_data.filter(
        (item) => item.quest_type === type
      )
      console.log(arr)
      this.$refs.ChooseQustion.chooseQuestionList = arr
      console.log(type)
      this.$refs.ChooseQustion.queryData.quest_type = type
      this.$refs.ChooseQustion.showDialog = true
      this.$refs.ChooseQustion.initData()
    },
    // 看题
    lookQsFn(type) {
      // 筛选出选的对应题目
      let arr = []
      if (this.formData.question_data.length > 0) {
        arr = this.formData.question_data.filter((item) => {
          return item.quest_type == type
        })
      }
      // console.log(arr)
      this.chayueList = arr
      this.showDialog = true
    },
    getQsList(val) {
      // console.log(val)
      val.forEach((item) => {
        this.formData.question_data.push(item)
      })
      if (this.formData.question_list.length === 0) {
        this.formData.question_list = val.map((item) => item.id)
      } else {
        this.formData.question_list.push(val.map((item) => item.id))
      }
    },
    getLength() {
      this.countList = [
        { type: 1, length: 0 },
        { type: 2, length: 0 },
        { type: 3, length: 0 },
        { type: 4, length: 0 },
      ]
      this.formData.question_data.forEach((item) => {
        this.countList[item.quest_type - 1].length++
      })
    },
    async createFn() {
      if (this.formData.question_data.length === 0) {
        return this.$message.warning('题目为空，请选择！')
      }
      let score = 0
      this.formData.check_question_list.forEach((item) => {
        score += Number(item.num) * item.score
      })
      if (score !== this.formData.total_score) {
        return this.$message.warning('选题总分数和试卷总分不一致!')
      }
      console.log(score)
      delete this.formData.question_data
      if (this.formData.id) {
        this.formData.question_list = this.formData.question_list.split(',')
        await editPaperApi(this.formData)
        this.$message.success('修改成功')
      } else {
        await addPaperApi(this.formData)
        this.$message.success('创建成功')
      }
      this.$emit('backPaper')
    },
    // 归属目录筛选
    changeHandler(val) {
      if (val === '') {
        this.directoryList = []
      }
      this.treeList.forEach((item) => {
        if (item.id === val) {
          this.directoryList = item.children
        }
      })
    },

    // 弹窗事件
    // 试题预览
    qsPreviewFn(id) {
      console.log(id)
      // 从问题列表筛选出对应的单个题目
      this.previewQuestion = this.chayueList.filter((item) => item.id === id)
      this.previewQuestion = this.previewQuestion[0]
      console.log(this.previewQuestion)
      // 如果是选择题
      if (
        this.previewQuestion.quest_type === 1 ||
        this.previewQuestion.quest_type === 2
      ) {
        this.options = JSON.parse(this.previewQuestion.quest_options)
        console.log('选项', this.options)
      }
      this.previewShow = true
    },
    // 查阅试题关闭事件
    lookClose() {
      this.questionList = []
    },
    // 试题预览关闭事件
    preClose() {
      this.previewQuestion = ''
      this.options = []
    },
    count(type) {
      // console.log(typeof type)
      let length = 0
      if (this.formData.question_data.length > 0) {
        length = this.formData.question_data.filter(
          (item) => item.quest_type === type
        )
      }
      console.log(length)
    },
    changNum(row) {
      // console.log(row)
      let idx = this.countList.findIndex((item) => item.type == row.type)
      console.log(this.countList[idx].length)

      if (row.num != this.countList[idx].length) {
        this.tipShow = true
      } else {
        this.tipShow = false
      }
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  border-bottom: 1px solid #ebebeb;
}
.tag {
  color: #606266;
}
.tag2 {
  color: #aaa;
}
</style>
